﻿using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.IO;
using System.Reflection;
using log4net;
using log4net.Config;
using PowerGui.AddOn.Interfaces;
using PowerGuiVsx.Core;

namespace PowerGui.AddOn
{
    public class PowerGuiComposer
    {
        private static ILog Log = LogManager.GetLogger(typeof (PowerGuiComposer));

        static PowerGuiComposer()
        {
            var fileInfo =
                new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "QuickConsoleLogConfig.xml"));

            XmlConfigurator.ConfigureAndWatch(fileInfo);

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = e.ExceptionObject as Exception;
            Log.Fatal("There was an unhandled exception! OMG WTF!", ex);
        }

        private static CompositionContainer _container;

        public static void Compose(object obj)
        {
            Compose(obj, true);
        }

        public static void Compose(object obj, bool initialize)
        {
            PowerGuiAssemblyLoader.LoadAssemblies();
            var assemblyUri = new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));

            var catalog = new DirectoryCatalog(assemblyUri.LocalPath);

            var c = GetContainer(catalog);

            if (initialize)
            {
                c.GetExportedValue<IPowerGui>().Initialize();
            }

            c.ComposeParts(obj);
        }

        public static void Compose(object obj, bool initialize, ComposablePartCatalog catalog)
        {
            var c = GetContainer(catalog);

            if (initialize)
            {
                c.GetExportedValue<IPowerGui>().Initialize();
            }

            c.ComposeParts(obj);
        }

        private static CompositionContainer GetContainer(ComposablePartCatalog catalog)
        {
            if (_container == null)
            {
                _container = new CompositionContainer(catalog);

            }
            return _container;
        }

        public static Version SupportedVersion
        {
            get
            {
                return new Version(Properties.Resources.SupportedVersion);
            }
        }
    }
}
